package tr.edu.ege.seagent.rdf.reader.tutorial;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.FileManager;

public class Organizer {
	public static void main(String[] args)
			throws java.lang.ClassNotFoundException, java.sql.SQLException {

		FileManager fManager = FileManager.get();
		fManager.addLocatorURL();
		Model linkedDataModel = fManager
				.loadModel("http://books.google.com/?id=1Nxy_E8Gds4C&pg=PP1&lpg=PP1&dq=Turkey+European+Union");

		StmtIterator iter = linkedDataModel.listStatements();
		while (iter.hasNext()) {
			String a; // subject
			String b; // predicate
			String c; // object

			Statement stmt = iter.nextStatement(); // get next statement
			Resource subject = stmt.getSubject(); // get the subject
			Property predicate = stmt.getPredicate(); // get the predicate
			RDFNode object = stmt.getObject(); // get the object

			a = skipSlashes(subject.toString());
			b = skipSlashes(predicate.toString());
			if (object instanceof Resource) {
				c = skipSlashes(object.toString());
			} else {
				// object is a literal
				c = "/" + skipSlashes(object.toString());
			}
			System.out.printf("%70s  %30s   %30s", a, b, c);
			System.out.println(" .");

		}

	}

	// skips the slashes in a given string (URIs in this code)
	private static String skipSlashes(String string) {
		int i = 0;
		int j = 0;
		while (j < countSlashes(string)) {
			if (string.charAt(i) == '/') {
				j += 1;
			}
			i += 1;
		}
		return string.substring(i);
	}

	// counts the number of slashes in a given string
	private static int countSlashes(String string) {
		int i = 0;
		int j = 0;
		// while there are more characters, check if there is another slash
		while (i < string.length()) {
			if (string.charAt(i) == '/') {
				j += 1;
			}
			i += 1;
		}
		return j;
	}
}